<script>
import OptionsManage from "@/views/product/trafficSource/optionsManage.vue";
import {
  getDataCycleOptions,
  getStoreNameOptions,
  downloadExcel
} from "@/views/product/trafficSource/api/index.js";
import { getData as getTrafficSourceOptions } from "@/views/product/trafficSource/api/options.js";
import { formatPercentage, isNull } from "@/utils/service";
import download from "@/plugins/download";
import { page } from "@/api/product/trafficSource";
import TbColumn from "@/components/table/tbColumn";
import ColumnManager from "@/components/table/columnManager.vue";
import ColumnFilter from "@/components/table/columnFilter.vue";
import ColumnFilterTags from "@/components/table/columnFilterTags.vue";
import { COLUMNS } from "@/views/product/trafficSource/columns";

/** 流量来源 */
export default {
  name: "trafficsSource",
  components: { ColumnFilterTags, ColumnFilter, ColumnManager, OptionsManage },
  computed: {
    /** 收费的流量来源名称列表*/
    tollTrafficSourceNames() {
      if (!this.trafficSourceOptions.length > 1) {
        return [];
      }
      return this.trafficSourceOptions[0].children.map(item => item.name);
      return this.trafficSourceOptions[0].children.map(item => item.name);
    },
    /** 免费的流量来源名称列表*/
    freeTrafficSourceNames() {
      if (!this.trafficSourceOptions.length > 1) {
        return [];
      }
      return this.trafficSourceOptions[1].children.map(item => item.name);
    },
    showTbColumns(){
      return this.tbColumns.filter(item => item.enabled && item.show)
    }
  },
  mounted() {
    this.getTrafficSourceOptions();
    this.loadTable();
  },
  data() {
    let _vm = this;
    return {
      columnFilterShow: true,
      storeNameOptions: {
        data: [],
        loading: false
      },
      trafficSourceOptions: [],
      dataCycleOptions: {
        data: [],
        loading: false
      },
      /** 搜索字段 */
      searchFiled: {
        storeName: "",
        productId: "",
        selectTrafficSource: [],
        dataCycle: ""
      },
      filterParamList: [],
      filterRefPrefix: "colFilter_",
      table: {
        tbLoading: false,
        /* 选中行数据 */
        sRows: [],
        data: [],
        pageNo: 1,
        pages: 0,
        pageSize: 30,
        pageCount: 0,
        sortField: "",
        sortMode: "DESC",
        handleSizeChange(pageSize) {
          if (pageSize === _vm.table.pageSize) {
            return;
          }
          _vm.table.pageSize = pageSize;
          _vm.loadTable();
        },
        handleCurrentChange(pageNo) {
          if (pageNo === _vm.table.pageNo) {
            return;
          }
          _vm.table.pageNo = pageNo;
          _vm.loadTable();
        },
        sRowChange(rows) {
          _vm.table.sRows = rows;
        }
      },
      tbColumns: COLUMNS
    };
  },
  methods: {
    refreshColumns(columns) {
      this.columnFilterShow = false
      this.tbColumns = TbColumn.buildArray(columns);
      this.$nextTick(() => {
        this.$refs.myTb.doLayout();
      });
      this.columnFilterShow = true
    },
    getTrafficSourceOptions() {
      getTrafficSourceOptions(this, {}, function(r) {
        this.trafficSourceOptions = r;
      }.bind(this));
    },
    getStoreNameOptions() {
      this.storeNameOptions.loading = true;
      getStoreNameOptions(this, function(r) {
        this.storeNameOptions.data = r;
      }.bind(this), function(r) {
        this.storeNameOptions.loading = false;
      }.bind(this));
    },
    getDataCycleOptions() {
      this.dataCycleOptions.loading = true;
      getDataCycleOptions(this, function(r) {
        this.dataCycleOptions.data = r;
      }.bind(this), function(f) {
        this.dataCycleOptions.loading = false;
      }.bind(this));
    },
    tableDataProvider() {
      return JSON.parse(JSON.stringify(this.table.data));
    },
    toRender(componentData) {
      this.table.data = componentData.tableList;
    },
    /** 将表格值转为百分比*/
    valueToPercentage(row, column, cellValue, index) {
      return !isNull(cellValue) ? formatPercentage(cellValue) : "-";
    },
    loadTable() {
      let param = {
        pageNo: this.table.pageNo,
        pageSize: this.table.pageSize,
        storeName: this.searchFiled.storeName,
        productId: this.searchFiled.productId,
        trafficsSourceNameList: this.searchFiled.selectTrafficSource,
        dataCycle: this.searchFiled.dataCycle,
        sortField: this.table.sortField,
        sortMode: this.table.sortMode,
        filterParams: TbColumn.buildReqParams(this.tbColumns)
      };
      // 追加过滤参数
      if (this.filterParamList.length !== 0) {
        param.filterParam = {};
        this.filterParamList.forEach(item => {
          param.filterParam[item.prop] = item.value;
        });
      }
      this.table.tbLoading = true;
      page(param).then(r => {
        this.table.data = r.list;
        this.table.pageNo = r.pageNo;
        this.table.pageCount = r.total;
        this.table.pageSize = r.pageSize;
        this.table.pages = r.pages;
      }).finally(() => {
        this.table.tbLoading = false;
      });
    },
    search() {
      this.loadTable();
    },
    clearableSearchInput() {
      this.searchFiled.storeName = "";
      this.searchFiled.productId = "";
      this.searchFiled.selectTrafficSource = [];
      this.searchFiled.dataCycle = "";
      this.loadTable();
    },
    download() {
      if (isNull(this.searchFiled.storeName)) {
        this.$message.warning("请选择店铺名称");
        return;
      }
      let param = {
        storeName: this.searchFiled.storeName,
        productId: this.searchFiled.productId,
        trafficsSourceNameListJson: JSON.stringify(this.searchFiled.selectTrafficSource),
        dataCycle: this.searchFiled.dataCycle
      };

      const fileName = this.searchFiled.storeName + this.searchFiled.dataCycle;

      downloadExcel(this, param, res => {
        download.excel(res.data, fileName);
        this.$message.success("下载成功");
      });
    },
    tableSortChange(column, prop, order) {
      if (!isNull(column.order)) {
        this.table.sortField = column.prop;
        if (column.order.startsWith("asc")) {
          this.table.sortMode = "ASC";
        } else {
          this.table.sortMode = "DESC";
        }
      } else {
        this.table.sortMode = "ASC";
      }
      this.loadTable();
    },
    tableRowStyle({ row, rowIndex }) {
      let r = {
        height: "20px"
      };
      if (this.tollTrafficSourceNames.includes(row.trafficsSource)) {
        r.color = "#ff4757";
        r.fontWeight = "bold";
      }
      return r;
    }
  }
};
</script>

<template>
  <div style="margin: 10px 0">
    <div class="header">
      <el-select
        @focus="getStoreNameOptions"
        style="width: 230px"
        size="mini" v-model="searchFiled.storeName" clearable filterable placeholder="请选择店铺名称">
        <el-option
          v-for="item in storeNameOptions.data"
          :key="item"
          :label="item"
          :value="item">
        </el-option>
      </el-select>

      <el-select
        clearable
        @focus="getDataCycleOptions"
        style="margin-left: 5px"
        size="mini"
        v-model="searchFiled.dataCycle"
        placeholder="请选择数据周期"
        :loading="dataCycleOptions.loading"
      >
        <el-option
          v-for="item in dataCycleOptions.data"
          :key="item"
          :label="item"
          :value="item">
        </el-option>
      </el-select>

      <el-cascader
        size="mini"
        style="width: 250px;margin-left: 5px;"
        @focus="getTrafficSourceOptions"
        v-model="searchFiled.selectTrafficSource"
        :options=trafficSourceOptions
        :props="{ multiple: true,label: 'name',value: 'name',emitPath: false}"
        collapse-tags
        clearable
        placeholder="请选择流量来源"
        popper-class="custom-cascade"
      >

      </el-cascader>

      <el-input type="number" size="mini" class="searchInput" v-model="searchFiled.productId"
                placeholder="商品编号(精确)" :clearable=true />
      <el-button type="primary" size="mini" icon="el-icon-search" @click="search()">搜索</el-button>
      <el-button type="info" size="mini" icon="el-icon-refresh" @click="clearableSearchInput()">清空</el-button>


      <template>
        <el-popconfirm
          confirm-button-text="好的"
          cancel-button-text="不用了"
          icon="el-icon-info"
          title="确定导出 Excel 表格文件吗？"
          @confirm="download"
        >
          <el-button slot="reference" style="margin-left: 10px" size="mini" type="success" icon="el-icon-download">导出
          </el-button>
        </el-popconfirm>
      </template>
      <div style="margin-top: 10px">
        <options-manage></options-manage>
        <column-manager style="margin-left: 5px" :columns="tbColumns" @refreshColumns="refreshColumns" />
      </div>
      <div style="margin-top: 5px">
        <column-filter-tags :columns="tbColumns" @closeItem="loadTable">
        </column-filter-tags>
      </div>
    </div>

    <div class="main">
      <el-table
        ref="myTb"
        @selection-change="table.sRowChange"
        v-loading="table.tbLoading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        height="70vh"
        :row-style="tableRowStyle"
        :cell-style="{padding:'0px'}"
        border
        :data="table.data"
        @sort-change="tableSortChange"
      >
        <el-table-column
          v-for="(item,index) in showTbColumns"
          :label="item.label"
          :prop="item.prop"
          :align="item.align"
          :width="item.width"
          :show-overflow-tooltip="item.showOverflowTooltip"
          :sortable="item.sortable"
          :formatter="item.formatter"
        >
          <template #header>
            <column-filter v-if="columnFilterShow" :column="item" @filterHandler="loadTable" :ref="item.getRef()">
            </column-filter>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="footer">
      <div>
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change=table.handleSizeChange
          @current-change=table.handleCurrentChange
          :total=table.pageCount
          :page-sizes="[30, 50, 100, 300]"
          :page-size=table.pageSize
          :page-count=table.pages
          :current-page=table.pageNo
        >
        </el-pagination>
      </div>
      <div>
        <span class="label">选中数据量 : </span>
        <span style="font-weight: bold">{{ table.sRows.length }}</span>
      </div>
    </div>

  </div>
</template>

<style>
.header {
  margin: 10px 0 10px 0
}

.searchInput {
  margin: 0 5px;
  width: 13%;
}

.main {
  margin: 10px 0 10px 0;
}

.footer {
  display: flex;
  justify-content: space-between;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #ff3f34;
  color: #b9ff75;
}

.custom-cascade {
  max-height: 600px; /* 设置弹出框的最大高度 */
  overflow-y: auto; /* 当内容超出最大高度时启用垂直滚动条 */
}
</style>